package com.ash.print;

import com.ash.print.template.InTemplate;
import com.ash.print.template.SpuTemplate;
import org.jetbrains.annotations.NotNull;

import java.awt.print.*;

public class PrintJobDemo {

    public static void main(String[] args) throws PrinterException {
        PrinterJob job = PrinterJob.getPrinterJob();

        PageFormat pageFormat = getPageFormat();

        InTemplate.TagInfo tagInfo = new InTemplate.TagInfo();
        tagInfo.setExpressNo("123456");
        tagInfo.setShelvesNo("1-23");
        tagInfo.setPickupCode("23456");
        tagInfo.setRecipientName("ash");
        tagInfo.setPrintDateTime("2024-06-26 09:37:00");
        tagInfo.setCargoType("敏感货");


        final Printable printable =  new SpuTemplate(null);

        job.setPageable(new Pageable() {
            @Override
            public int getNumberOfPages() {
                return 1;
            }

            @Override
            public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
                return pageFormat;
            }

            @Override
            public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {

                return printable;
            }
        });

        job.print();
    }

    private static @NotNull PageFormat getPageFormat() {
        // 创建Paper对象
        Paper paper = new Paper();

        // 计算76mm和130mm对应的points值
        int widthInPoints = (int) Math.round(76 * 2.8346);
        int heightInPoints = (int) Math.round(130 * 2.8346);
        // 设置纸张的宽度和高度（单位是points，1英寸=72 points）
        paper.setSize(widthInPoints, heightInPoints);

        int leftMargin = 0;
        int rightMargin = 0;
        int topMargin = 0;
        int bottomMargin = 0;

        // 将边距从毫米转换为points
        int leftMarginInPoints = (int) Math.round(leftMargin * 2.8346);

        int rightMarginInPoints = (int) Math.round(rightMargin * 2.8346);

        int topMarginInPoints = (int) Math.round(topMargin * 2.8346);
        int bottomMarginInPoints = (int) Math.round(bottomMargin * 2.8346);

        double imageableWidth = paper.getWidth() - (leftMarginInPoints + rightMarginInPoints);
        double imageableHeight = paper.getHeight() - (topMarginInPoints + bottomMarginInPoints);

        // 设置可打印区域的左、右、上、下边距（同样以points为单位）
        paper.setImageableArea(leftMarginInPoints, topMarginInPoints, imageableWidth, imageableHeight);

        PageFormat pageFormat = new PageFormat();
        // 将Paper对象应用到PageFormat中
        pageFormat.setPaper(paper);
        return pageFormat;
    }
}
